package com.cong.security.app.authentication;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cong.security.core.code.CodeException;
import com.cong.security.core.constant.LoginType;
import com.cong.security.core.properties.SecurityProperties;
import com.cong.security.core.support.SimpleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	/**
	 * 工具类，将authentication转换成为json
	 */
	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private SecurityProperties securityProperties;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		if (exception instanceof CodeException) {
			if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
				response.setContentType("application/json;charset=UTF-8");
				response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
				response.setStatus(HttpStatus.OK.value());
			} else {
				// 不是json，调用父类方法(跳转)
				super.onAuthenticationFailure(request, response, exception);
			}
		} else if (exception instanceof InternalAuthenticationServiceException) {
			// 默认是未绑定
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
			response.setStatus(HttpStatus.OK.value());
		} else {
			log.info("不在捕获的错误范围中,进行其他处理");
			// 默认是未绑定
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse("unknown Exception")));
			response.setStatus(HttpStatus.OK.value());
		}
	}
}
